#include "stdafx.h"
#include "Game.hpp"
#include "SFML\Window\Event.hpp"
#include <iostream>
#include "GameScreen.hpp"

//Static
sf::RenderWindow rh::Game::_renderWindow;

rh::Game::Game(sf::String name, int screenWidth, int screenHeight)
{
#ifdef _DEBUG
	std::cout << "Game object \"" << std::string(name) << "\" created.test\nWidth: " << screenWidth << "\nHeight: " << screenHeight << " \n";
#endif
	_name = name;
	_screenWidth = screenWidth;
	_screenHeight = screenHeight;

	_gameState = rh::Game::GameState::Uninitialized;
}


rh::Game::~Game()
{
};

//Methods

void rh::Game::GameLoop(void)
{
	sf::Event currentEvent;
	_renderWindow.pollEvent(currentEvent);
	GameLogic();
	DrawLogic();
	if (currentEvent.type == sf::Event::Closed)
		_gameState = Game::GameState::Exiting;

};

void rh::Game::Start()
{
	if(_gameState != Uninitialized)
		return;
	
	_renderWindow.create(sf::VideoMode(_screenWidth,_screenHeight,32),_name);

	while(!IsExiting())
	{
		GameLoop();
	}

	_renderWindow.close();
}

const sf::Time rh::Game::GetApplicationRunningTime()
{
	return _masterClock.getElapsedTime();
}

const sf::Time rh::Game::GetElapsedTime()
{
	return _updateClock.restart();
}

bool rh::Game::IsExiting()
{
	if(_gameState == Game::Exiting) 
		return true;
	else 
		return false;
}

void rh::Game::DrawLogic(void)
{
	_renderWindow.clear();
	for(std::vector<rh::GameScreen*>::iterator iterator = _gameScreens.begin(); iterator != _gameScreens.end(); ++iterator)
	{
		(**iterator).Draw(_renderWindow, sf::RenderStates::Default);
	}
	_renderWindow.display();
}

void rh::Game::GameLogic(void)
{
	sf::Time totalElapsedTime = _masterClock.getElapsedTime();
	sf::Time elapsedTime = _updateClock.restart();
	if(elapsedTime.asMilliseconds() >= MAX_FRAME_TIME_mS)
		elapsedTime = sf::milliseconds(MAX_FRAME_TIME_mS);

	for(std::vector<rh::GameScreen*>::iterator iterator = _gameScreens.begin(); iterator != _gameScreens.end(); ++iterator)
	{
		(**iterator).Update(elapsedTime, totalElapsedTime);
	}
	rh::KeyboardInput::Update(elapsedTime, totalElapsedTime);
}